import json
import os
from datetime import datetime
import logging

class GiftLedger:
    def __init__(self, ledger_type):
        self.filename = f"{ledger_type}_ledger.json"
        self.records = []
        self.load_records()
        self._need_save = False

    def load_records(self):
        if os.path.exists(self.filename):
            try:
                with open(self.filename, 'r', encoding='utf-8') as f:
                    self.records = json.load(f)
                logging.info(f"Successfully loaded records from {self.filename}")
            except Exception as e:
                logging.error(f"Failed to load records from {self.filename}: {e}")

    def save_records(self):
        if self._need_save:
            try:
                with open(self.filename, 'w', encoding='utf-8') as f:
                    json.dump(self.records, f, ensure_ascii=False, indent=2)
                self._need_save = False
                logging.info(f"Successfully saved records to {self.filename}")
            except Exception as e:
                logging.error(f"Failed to save records to {self.filename}: {e}")

    def add_record(self, data):
        record_id = len(self.records) + 1
        data['id'] = record_id
        data['date'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.records.append(data)
        self._need_save = True
        logging.info(f"Added a new record with ID {record_id}")
        return record_id

    def delete_record(self, record_id):
        self.records = [r for r in self.records if r['id'] != record_id]
        self._need_save = True
        logging.info(f"Deleted record with ID {record_id}")

    def update_record(self, record_id, new_data):
        for record in self.records:
            if record['id'] == record_id:
                record.update(new_data)
                self._need_save = True
                logging.info(f"Updated record with ID {record_id}")
                return True
        return False